from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.cartser import CartSerializer
from cart.models import CartModel
from utils.authorization import MyAuthentication


# Create your views here.


class AddCart(APIView):
    authentication_classes = [MyAuthentication]

    def post(self, request):
        user = request.data.get('user')
        course = request.data.get('course')
        if user and course:
            info = CartModel.objects.filter(user=user, course=course).first()
            if info:
                return Response({"message": "课程已存在"})
            else:
                ser = CartSerializer(data=request.data)
                if ser.is_valid():
                    ser.save()
                    return Response({"message": "添加购物车成功"})
                else:
                    return Response({"message": "添加购物车失败"})
        else:
            return Response({"detail": '参数错误'})


class ListCart(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        user = request.query_params.get('user', "")
        if user == "":
            return Response({"detail": '参数错误'})
        cart = CartModel.objects.filter(user=user)
        ser = CartSerializer(cart, many=True)
        return Response({"message": "ok", "data": ser.data})


class ChangeOne(APIView):
    authentication_classes = [MyAuthentication]

    def put(self, request):
        id = request.data.get('id', "")
        if id == "":
            return Response({"detail": "参数错误"})
        cart = CartModel.objects.filter(id=id).first()
        cart.select = not cart.select
        cart.save()
        return Response({"message": "修改成功"})


class ChangeAll(APIView):
    authentication_classes = [MyAuthentication]

    def put(self, request):
        user = request.data.get('user')
        select = request.data.get('select')
        if user == "":
            return Response({"detail": "参数错误"})
        cart = CartModel.objects.filter(user=user)
        for i in cart:
            i.select = select
            i.save()
        return Response({"message": "修改成功"})


class DelCart(APIView):
    authentication_classes = [MyAuthentication]

    def delete(self, request):
        id = request.query_params.get('id', "")
        if id == "":
            return Response({"detail": "参数错误"})
        cart = CartModel.objects.filter(id=id).first()
        cart.delete()
        return Response({"message": "删除成功"})
